package top.yifengxiner.framework.shiro.service;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.yifengxiner.common.core.pojo.AjaxResult;
import top.yifengxiner.common.core.pojo.entity.SysUser;
import top.yifengxiner.common.core.pojo.vo.LoginBody;
import top.yifengxiner.common.exception.user.PasswordErrorException;
import top.yifengxiner.common.exception.user.UserNotExistsException;
import top.yifengxiner.common.utils.TokenUtils;
import top.yifengxiner.system.service.SysUserService;

/**
 * @author ：baixiao
 * @date ：Created in 2021/5/6 9:10
 * @description：登录逻辑处理层
 * @modified By：
 * @version: $0.0.1
 */
@Component
public class SysLoginService
{
    @Autowired
    private SysUserService userService;

    @Autowired
    private  SysPasswordService passwordService;
    /**
     * 登录验证
     * @param loginBody
     * @return
     */
    public AjaxResult login(LoginBody loginBody)
    {
        AjaxResult ajaxResult = AjaxResult.success();
        UsernamePasswordToken token = new UsernamePasswordToken(loginBody.getUsername(),loginBody.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            String tk = TokenUtils.createToken(loginBody.getUsername());
            System.out.println(tk);
            ajaxResult.put("token",tk);
            return ajaxResult;
        }
        catch (AuthenticationException e)
        {
            return AjaxResult.error("用户名密码错误");
        }
    }

    /**
     * 验证用户名和密码得到用户
     * @param username
     * @param password
     * @return
     */
    public SysUser getUser(String username,String password)
    {
        SysUser user = userService.selectUserByUsername(username);
        if(!user.getPassword().equals(passwordService.encryptPassword(user.getUserName(),password,user.getSalt())))
        {
            throw  new PasswordErrorException("验证模块","密码错误");
        }
        if(user == null)
        {
            throw  new UserNotExistsException();
        }
        return user;
    }
}
